package com.renli.intercept;


import com.renli.pojo.Login;
import com.renli.service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckTokenIntercept implements HandlerInterceptor {
    @Autowired
    private LoginService loginService;

    //拦截实现的方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        System.out.println("========  CheckTokenIntercept  拦截器 ================ ");
        //  响应的设置
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin")); // *允许任意地址访问，当前解决跨域后携带cookie问题
        response.setHeader("Access-Control-Allow-Credentials", "true"); //是否包含cookie，如果不包含，可省略
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,PATCH,PUT,OPTIONS,DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization,Cookie,Accept,Token,Origin");
        //获得头部信息
        String token = request.getHeader("authorization");
        //
        if (token != null && token.trim().length() > 0) {//   如果   没有token  没登录  有 token 数据库没有   跳Exception控制器
            //验证数据库  中是否存在
            //把用户保存shiro
            Login login = (Login) SecurityUtils.getSubject().getPrincipal();//29
            //延长生命  token
            String redisToken = loginService.checkToken(login.getUsername());
            if (token.equals(redisToken)) {
                return true;
            }
        }
        System.out.println("拦截器..............");
        request.setAttribute("msg", "未登录");
        request.getRequestDispatcher("/notLogin").forward(request, response);
        return true;
    }


}
